package indi.mozping.pc;

import indi.mozping.tools.SleepTools;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author by mozping
 * @Classname Pc ������������ʵ�֣�ʹ���������У�����ʵ�ַ�ʽ�Ƚϼ򵥣�������Ҫ���߳�֮���ͬ��
 * ����ͬ������������̵߳���������������ͬ����������
 * �����ǲ���Ҫ�Լ�����ͬ������ͬ�����з�����������ͬ��������
 * @Description TODO
 * @Date 2019/3/5 20:33
 */
public class Pc {

    private static AtomicInteger integer = new AtomicInteger(0);

    public static void main(String[] args) {
        //BlockingQueue<Integer> blockingQueue = new ArrayBlockingQueue<>(100);
        BlockingQueue<Integer> blockingQueue = new LinkedBlockingQueue<>(100);
        Producer p = new Producer(blockingQueue);
        Consumer c1 = new Consumer(blockingQueue);
        Consumer c2 = new Consumer(blockingQueue);
        new Thread(p).start();
        new Thread(p).start();
        new Thread(c1).start();
        new Thread(c2).start();
    }


    static class Producer implements Runnable {

        BlockingQueue<Integer> blockingQueue;

        Producer(BlockingQueue blockingQueue) {
            this.blockingQueue = blockingQueue;
        }

        @Override
        public void run() {
            while (true) {
                int i = integer.getAndIncrement();
                blockingQueue.add(i);
                System.out.println("������������Ʒ�����Ϊ" + i);
                SleepTools.randomMs(5000);
            }
        }
    }

    static class Consumer implements Runnable {

        BlockingQueue<Integer> blockingQueue;

        Consumer(BlockingQueue blockingQueue) {
            this.blockingQueue = blockingQueue;
        }

        @Override
        public void run() {
            while (true) {
                Integer element = null;
                try {
                    element = blockingQueue.take();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("����������һ�������Ϊ" + element);
                SleepTools.randomMs(5000);
            }
        }
    }
}
